﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：周传雄 
    //
    // 文件名：DistributePlanList.cs
    // 文件功能描述：发票管理
    // 创建标识：周传雄2009-05-12
    //
    // 修改标识：李刚 2009-6-7
    // 修改描述：发票的审核取消 将原有三种状态： 未审核，审核通过，审核不通过；
    //           改为 未提交，已提交 两种状态。
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Collections.Generic;
using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;
using System.Data.SqlClient;
using HZ.Common;

namespace HZ.DrugTrade.Web.Enterprise.InvoiceManage
{
    public partial class InvocieList : BasePage
    {
        IBLL_Purchase ip = Factory.BLL_Purchase();

        public InvocieList()
        {
            this.ModuleNo = Module.发票管理.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                QueryResult();
            }
        }
        /// <summary>
        /// 发票列表
        /// </summary>
        private void QueryResult()
        {
            IList<Model.View.Invoice> LisInvoice = new List<Model.View.Invoice>();
            Model.Query.Invoice qryCondition = new Model.Query.Invoice();
            User user = CurrentAccount.GetUser();
            qryCondition.CompanyID_PS = user.Org.OrgID;
            qryCondition.InvoiceTimeFrom = new HZ.Common.ConvertHelper(txtTimeFrom.Text.ToString().Trim()).ToDateTime;
            qryCondition.InvoiceTimeTo = new HZ.Common.ConvertHelper(txtTimeTo.Text.ToString().Trim()).ToDateTime;
            qryCondition.HospitalName = txtHospitalName.Text.ToString().Trim();
            qryCondition.InvoiceID = txtInvoiceID.Text.ToString().Trim();
            switch (ddlAuditStatus.SelectedItem.Value)
            {
                //0未审核；1通过；2不通过
                //改为 0 未提交，1 已提交
                case "":
                    qryCondition.AuditStatus = null;
                    break;
                case "0":
                    qryCondition.AuditStatus = 0;
                    break;
                case "1":
                    qryCondition.AuditStatus = 1;
                    break;
                //case 3:
                //    qryCondition.AuditStatus = 2;
                //    break;
            }
            qryCondition.SortFields = " AddDate desc ";
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalCount = 0;
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();
            LisInvoice = iPurchase.GetInvoiceByWhere(qryCondition, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            AspNetPager1.RecordCount = totalCount;
            gvwInvoiceList.DataSource = LisInvoice;
            gvwInvoiceList.DataBind();

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            QueryResult();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSelect_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            QueryResult();
        }
        /// <summary>
        /// 删除发票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int nSuccess = 0;
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();

            string[] InvoiceSerialIDs = Request.Form["ChkID"].ToString().Split(',');

            IList<Invoice> invoiceList = new List<Invoice>();
            foreach (var item in InvoiceSerialIDs)
            {
                invoiceList.Add(new Invoice() { InvoiceSerialID = item });
            }

            nSuccess = iPurchase.DelInvoice_Batch(invoiceList);

            if (nSuccess == 1)
            {
                HZ.Web.WebUtil.Alert("操作成功", this);

                QueryResult();
            }
            else if (nSuccess == 1)
            {
                HZ.Web.WebUtil.Alert("发票已提交！", this);

                QueryResult();
            }
            else if (nSuccess == 0)
            {
                HZ.Web.WebUtil.Alert("操作失败", this);
                QueryResult();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strAA"></param>
        /// <returns></returns>
        public string getA(object strAA)
        {
            return "  <a href='InvoiceAddNo.aspx?isID=" + strAA.ToString() + "'>修改</a>";
        }

        /// <summary>
        /// 提交发票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void btnSubmit_Click(object sender, EventArgs e)
        //{
        //    string[] InvoiceSerialIDs = Request.Form["ChkID"].ToString().Split(',');

        //    List<Invoice> invoiceList = new List<Invoice>();
        //    foreach (var item in InvoiceSerialIDs)
        //    {
        //        invoiceList.Add(new Invoice() { InvoiceSerialID = item, AuditPerson = CurrentAccount.GetUser().UserID });
        //    }

        //    if (ip.ConfirmInvoice_Batch(invoiceList) == 1)
        //    {
        //        //
        //        HZ.Web.WebUtil.Alert("成功将发票提交给医疗机构！", this);
        //        QueryResult();
        //    }
        //    else
        //    {
        //        HZ.Web.WebUtil.Alert("操作失败！", this);
        //    }

        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("InvoiceAddNo.aspx");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwInvoiceList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            IBLL_Purchase iPurchase = Factory.BLL_Purchase();


            if (e.CommandName == "submit")//提交发票
            {
                Model.Query.InvoiceDistribution qInvoiceDistributionList = new HZ.DrugTrade.Model.Query.InvoiceDistribution();
                qInvoiceDistributionList.InvoiceSerialID = e.CommandArgument.ToString();
                int total = 0;
                IList<HZ.DrugTrade.Model.View.InvoiceDistribution> InvoiceDistributionList = iPurchase.GetInvoiceDistributionByWhere(qInvoiceDistributionList, 1, 0, out total);
                if (total == 0)
                {
                    HZ.Web.WebUtil.Alert("发票单中没有任何产品，无法提交！", this);
                    return;
                }
                
                HZ.DrugTrade.Model.Invoice invoice = new Invoice();
                invoice.InvoiceSerialID = e.CommandArgument.ToString();
                invoice.AuditPerson = CurrentAccount.GetUser().UserID;
                List<Invoice> invoiceList = new List<Invoice>();
                invoiceList.Add(invoice);
                string[] a=new string[0];
                if (ip.ConfirmInvoice_Batch(invoiceList,a) == 1)
                {
                    PageInfo("发票单提交成功！", this.Request.RawUrl);
                }
                else
                {
                    PageError("提交失败！", "");
                }
            }
            if (e.CommandName == "Revoke")//撤回发票
            {
                IList<Model.View.InvoiceDistribution> ListInvoiceDistribution = new List<Model.View.InvoiceDistribution>();
                Model.Query.InvoiceDistribution qryCondition = new Model.Query.InvoiceDistribution();
                User user = CurrentAccount.GetUser();
                qryCondition.CompanyID_PS = user.Org.OrgID;
                qryCondition.InvoiceSerialID = e.CommandArgument.ToString();


                int totalCount = 0;
                ListInvoiceDistribution = iPurchase.GetInvoiceDistributionByWhere(qryCondition, 1, 0, out totalCount);
                if (ListInvoiceDistribution.Count == 0)
                {
                    HZ.Web.WebUtil.Alert("空发票！");
                    return;
                }
                if (ListInvoiceDistribution[0].InvoicePaySerialID != null && ListInvoiceDistribution[0].InvoicePaySerialID.Trim() != string.Empty)
                {
                    HZ.Web.WebUtil.Alert("已建立结算单的发票不能撤回！");
                    return;
                }
                if (ListInvoiceDistribution[0].AuditStatus == 0)
                {
                    HZ.Web.WebUtil.Alert("此发票还未提交！");
                    return;
                }


                List<Invoice> invoiceList = new List<Invoice>();
                invoiceList.Add(new Invoice() { InvoiceSerialID = e.CommandArgument.ToString(), AuditStatus = 0, AuditPerson = CurrentAccount.GetUser().UserID });
                int state = iPurchase.DropInvoice_Batch(invoiceList);
                if (state == 1)
                {
                    HZ.Web.WebUtil.Alert("成功撤回发票！", this);

                }
                else if (state == 2)
                {
                    HZ.Web.WebUtil.Alert("已建立结算单的发票不能撤回！", this);

                }
                else
                {
                    HZ.Web.WebUtil.Alert("操作失败！", this);
                }
                QueryResult();
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Model.Query.Invoice qryCondition = new Model.Query.Invoice();
            User user = CurrentAccount.GetUser();
            qryCondition.CompanyID_PS = user.Org.OrgID;
            qryCondition.InvoiceTimeFrom = new HZ.Common.ConvertHelper(txtTimeFrom.Text.ToString().Trim()).ToDateTime;
            qryCondition.InvoiceTimeTo = new HZ.Common.ConvertHelper(txtTimeTo.Text.ToString().Trim()).ToDateTime;
            qryCondition.HospitalName = txtHospitalName.Text.ToString().Trim();
            qryCondition.InvoiceID = txtInvoiceID.Text.ToString().Trim();
            switch (ddlAuditStatus.SelectedItem.Value)
            {
                //0未审核；1通过；2不通过
                //改为 0 未提交，1 已提交
                case "":
                    qryCondition.AuditStatus = null;
                    break;
                case "0":
                    qryCondition.AuditStatus = 0;
                    break;
                case "1":
                    qryCondition.AuditStatus = 1;
                    break;
            }
            qryCondition.SortFields = " AddDate desc ";
            string where = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition<HZ.DrugTrade.Model.Query.Invoice>(qryCondition, true);
            string sql = string.Format(@"SELECT InvoiceID 发票号,Hospitalname 采购医疗机构,TotalAmount 发票总金额,DistributionCount 配送单数量,InvoiceTime 发票日期,
                                        AuditTime 提交时间,AddDate 录入时间,NoPassReason 审核未通过原因,case AuditStatus when 0 then '未提交' else '已提交' end as 发票状态 FROM View_Invoice WHERE 1=1 {0}", where);
            HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sql), "", "发票管理.xls");
        }

    }
}
